package com.lnlyj.media.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lnlyj.media.R;
import com.lnlyj.media.data.AlbumItem;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.ListPopupWindow;

import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

/**
 * wanglei 2020-04-17
 */
public class MediaToolBar extends LinearLayout {

    private ImageView closeIv;
    private TextView titleTv;
    private Button sendBtn;
    private ImageView animIv;

    private ListPopupWindow popupWindow;
    private PopAdapter popAdapter;

    private List<AlbumItem> albumItems = new ArrayList<>();
    private AlbumItem currentAlbum;

    private OnAlbumChangeListener albumChangeListener = null;
    private OnCloseListener closeListener;
    private OnSelectorListener selectorListener;

    public MediaToolBar(Context context) {
        this(context, null);
    }

    public MediaToolBar(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MediaToolBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    @SuppressLint("RestrictedApi")
    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        View.inflate(context, R.layout.layout_toolbar, this);

        closeIv = findViewById(R.id.iv_close);
        titleTv = findViewById(R.id.tv_album);
        sendBtn = findViewById(R.id.btn_send);
        animIv = findViewById(R.id.iv_anim);

        closeIv.setOnClickListener(view -> {
            if (closeListener != null) {
                closeListener.onClose();
            }
        });

        sendBtn.setOnClickListener(view -> {
            if (selectorListener != null) {
                selectorListener.onSelector();
            }
        });

        ((ViewGroup) titleTv.getParent()).setOnClickListener(view -> {
            if (popupWindow != null) {
                popupWindow.show();
            }
        });
    }

    private void notifyAlbumChange(int position) {

        if (albumItems.size() == 0) {
            return;
        }

        if (position == -1) {
            position = 0;
        }


        AlbumItem item = albumItems.get(position);
        if (Objects.equals(item, currentAlbum)) {
            return;
        }
        currentAlbum = item;
        popAdapter.notifyDataSetChanged();
        if (albumChangeListener != null) {
            albumChangeListener.onAlbumChange(currentAlbum);
        }

        titleTv.setText(currentAlbum.getName());
    }

    private void buildPopupWindow() {
        popupWindow = new ListPopupWindow(getContext());
        popupWindow.setAnchorView(this);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFFFFF")));
        popupWindow.setModal(true);
        popupWindow.setHeight(WRAP_CONTENT);
        popupWindow.setAnimationStyle(R.style.MediaPopAnim);
        popupWindow.setAdapter(popAdapter = new PopAdapter());
        popupWindow.setOnItemClickListener((adapterView, view, position, l) -> {
            notifyAlbumChange(position);
            popupWindow.dismiss();
        });

        try {
            // 设置展开最大条目数，否则在滑动的时候回导致重新设置高度
            Field field = popupWindow.getClass().getDeclaredField("mListItemExpandMaximum");
            field.setAccessible(true);
            field.setInt(popupWindow, 4);

        } catch (IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    public void setAlbumData(List<AlbumItem> list) {

        if (popupWindow == null) {
            buildPopupWindow();
        }

        this.albumItems.clear();

        if (list != null && !list.isEmpty()) {
            albumItems.addAll(list);
        }

        int position = currentAlbum == null ? -1 : albumItems.indexOf(currentAlbum);

        notifyAlbumChange(position);
    }

    public void setTitle(String title) {
        titleTv.setText(title);
    }

    public void setSendButtonText(String text) {
        sendBtn.setText(text);
    }

    public void setSendButtonEnabled(boolean enabled) {
        sendBtn.setEnabled(enabled);
    }

    public AlbumItem getCurrentAlbum() {
        return currentAlbum;
    }

    public void setAlbumChangeListener(OnAlbumChangeListener albumChangeListener) {
        this.albumChangeListener = albumChangeListener;
    }

    public void setCloseListener(OnCloseListener closeListener) {
        this.closeListener = closeListener;
    }

    public void setSelectorListener(OnSelectorListener selectorListener) {
        this.selectorListener = selectorListener;
    }

    public interface OnAlbumChangeListener {
        void onAlbumChange(AlbumItem item);
    }

    public interface OnCloseListener {
        void onClose();
    }

    public interface OnSelectorListener {
        void onSelector();
    }

    private class PopAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return albumItems.size();
        }

        @Override
        public AlbumItem getItem(int i) {
            return albumItems.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            ViewHolder holder = null;

            if (view == null) {
                view = View.inflate(viewGroup.getContext(), R.layout.item_pop_album, null);
                holder = new ViewHolder();
                holder.album = view.findViewById(R.id.iv_item_album);
                holder.name = view.findViewById(R.id.tv_item_album);

                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }

            AlbumItem item = getItem(i);

            holder.name.setText(view.getContext().getString(R.string.item_album_name, item.getName(), item.getCount()));
            Glide.with(holder.album.getContext()).load(item.getIconUri()).skipMemoryCache(false).placeholder(R.drawable.ic_image_default).crossFade(0).into(holder.album);

            return view;
        }

        class ViewHolder {
            ImageView album;
            TextView name;
        }
    }
}
